package com.pp.tourism.web.controller;

import com.pp.tourism.web.dto.ApiResponse;
import com.pp.tourism.web.pojo.User;
import com.pp.tourism.web.service.LoginService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Api(description = "登录登出接口")
@Slf4j
@RestController
public class LoginLogoutController {

    private static final String SESSION_KEY = "USERNAME";

    @Autowired
    private LoginService loginService;

    @ApiOperation("登录接口")
    @PostMapping("/api/login")
    public ApiResponse login(@RequestBody Map<String,Object> param , HttpSession session) {
        String username = param.get("username").toString().trim();
        String password = param.get("password").toString().trim();
        User user = loginService.login(username, password);
        session.setAttribute(SESSION_KEY, user);
        log.info("登录成功: " + user.getPermission() + "用户: " + user.getUsername());
        return ApiResponse.ok(user);
    }

    @ApiOperation("登出接口")
    @PostMapping("/api/logout")
    public ApiResponse logout(HttpSession session){
        session.removeAttribute(SESSION_KEY);
        log.info("登出成功");
        return ApiResponse.ok("ok");
    }
}
